import Vue from 'vue'
import VueRouter from 'vue-router'
import LayoutView from '../views/LayoutView.vue'

Vue.use(VueRouter)

const isAuthenticated = localStorage.getItem('token-sqf');

const routes = [
  {
    path: '',
    component: LayoutView,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: () => import(/* webpackChunkName: "home" */ '../views/HomeView.vue')
      },
      {
        path: '/video',
        name: 'video',
        component: () => import(/* webpackChunkName: "role" */ '../views/wish/VideoView.vue')
      },
      {
        path: '/wish',
        name: 'Wish',
        component: () => import(/* webpackChunkName: "wish" */ '../views/wish/WishView.vue')
      },
      {
        path: '/three',
        name: 'three',
        component: () => import(/* webpackChunkName: "wish" */ '../views/wish/ThreeView.vue')
      },
      {
        path: '/two',
        name: 'two',
        component: () => import(/* webpackChunkName: "wish" */ '../views/wish/TwoView.vue')
      },
      {
        path: '/register',
        name: 'Register',
        component: () => import(/* webpackChunkName: "about" */ '../views/wish/RegisterView.vue')
      },
      {
        path: '/hello',
        name: 'hello',
        component: () => import(/* webpackChunkName: "about" */ '../views/wish/HelloView.vue')
      },
      {
        path: '/one',
        name: 'one',
        component: () => import(/* webpackChunkName: "about" */ '../views/wish/OneView.vue')
      },
    ]
  },
  
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "about" */ '../views/LoginView.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
console.log(isAuthenticated, '-------------')

router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
   // 在有token的情况下不让用户再次访问login
  else if (to.name === 'Login' && isAuthenticated) next({ path: '/' })
  // 如果用户未能验证身份，则 `next` 会被调用两次
  else next()
})


export default router
